#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
第三步：技术分析系统 - 优化版本
专门为每周2-3%收益目标设计的技术分析系统
"""

import sys
import os
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
import warnings
import time
warnings.filterwarnings('ignore')

sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from real_data_fetcher import RealDataFetcher

class OptimizedTechnicalAnalysis:
    """优化版技术分析系统"""
    
    def __init__(self):
        self.data_fetcher = RealDataFetcher()
        
        # 专门针对周收益的技术分析参数
        self.weekly_params = {
            'short_ma': 5,      # 短期均线
            'medium_ma': 10,    # 中期均线
            'long_ma': 20,      # 长期均线
            'rsi_period': 6,    # RSI周期（适合短期）
            'macd_fast': 8,     # MACD快线
            'macd_slow': 17,    # MACD慢线
            'macd_signal': 9,   # MACD信号线
            'volume_ma': 5,     # 成交量均线
            'min_data_points': 30  # 最少数据点
        }
        
        # 技术评分权重（专门为周收益优化）
        self.scoring_weights = {
            'trend_score': 0.35,        # 趋势评分权重
            'momentum_score': 0.25,     # 动量评分权重
            'volume_score': 0.20,       # 成交量评分权重
            'volatility_score': 0.10,   # 波动率评分权重
            'position_score': 0.10      # 价格位置评分权重
        }
        
        # 统计数据
        self.analysis_stats = {
            'total_stocks': 0,
            'successful_analysis': 0,
            'failed_analysis': 0,
            'avg_data_points': 0,
            'start_time': None,
            'end_time': None
        }
        
    def print_header(self, title):
        """打印标题"""
        print(f"\n{'='*80}")
        print(f"📈 {title}")
        print(f"{'='*80}")
        
    def calculate_ma(self, data, period):
        """计算移动平均线"""
        return data.rolling(window=period, min_periods=1).mean()
        
    def calculate_ema(self, data, period):
        """计算指数移动平均线"""
        return data.ewm(span=period, adjust=False).mean()
        
    def calculate_rsi(self, data, period=6):
        """计算RSI指标（优化周期）"""
        delta = data.diff()
        gain = (delta.where(delta > 0, 0)).rolling(window=period, min_periods=1).mean()
        loss = (-delta.where(delta < 0, 0)).rolling(window=period, min_periods=1).mean()
        
        # 避免除零错误
        rs = gain / (loss + 1e-10)
        rsi = 100 - (100 / (1 + rs))
        return rsi
        
    def calculate_macd(self, data):
        """计算MACD指标（优化参数）"""
        ema_fast = self.calculate_ema(data, self.weekly_params['macd_fast'])
        ema_slow = self.calculate_ema(data, self.weekly_params['macd_slow'])
        macd_line = ema_fast - ema_slow
        signal_line = self.calculate_ema(macd_line, self.weekly_params['macd_signal'])
        histogram = macd_line - signal_line
        
        return {
            'macd': macd_line,
            'signal': signal_line,
            'histogram': histogram
        }
        
    def calculate_volatility(self, data, period=10):
        """计算波动率"""
        returns = data.pct_change().dropna()
        volatility = returns.rolling(window=period, min_periods=1).std() * np.sqrt(252) * 100
        return volatility
        
    def get_stock_data(self, stock_code, days=60):
        """获取股票数据"""
        try:
            data = self.data_fetcher.get_stock_data(stock_code, days)
            if data is not None and not data.empty and len(data) >= self.weekly_params['min_data_points']:
                return data
            return None
        except Exception as e:
            print(f"   ❌ 获取数据失败: {e}")
            return None
            
    def analyze_trend(self, data):
        """分析趋势（专门为周收益优化）"""
        try:
            close = data['close']
            
            # 计算均线
            ma5 = self.calculate_ma(close, self.weekly_params['short_ma'])
            ma10 = self.calculate_ma(close, self.weekly_params['medium_ma'])
            ma20 = self.calculate_ma(close, self.weekly_params['long_ma'])
            
            # 获取最新值
            current_price = close.iloc[-1]
            ma5_current = ma5.iloc[-1]
            ma10_current = ma10.iloc[-1]
            ma20_current = ma20.iloc[-1]
            
            # 趋势评分
            trend_score = 0
            trend_desc = ""
            
            # 多头排列检查
            if current_price > ma5_current > ma10_current > ma20_current:
                trend_score = 95
                trend_desc = "强多头"
            elif current_price > ma5_current > ma10_current:
                trend_score = 80
                trend_desc = "多头"
            elif current_price > ma5_current:
                trend_score = 65
                trend_desc = "偏多"
            elif current_price > ma10_current:
                trend_score = 55
                trend_desc = "震荡偏多"
            elif current_price < ma5_current < ma10_current < ma20_current:
                trend_score = 5
                trend_desc = "强空头"
            elif current_price < ma5_current < ma10_current:
                trend_score = 20
                trend_desc = "空头"
            elif current_price < ma5_current:
                trend_score = 35
                trend_desc = "偏空"
            else:
                trend_score = 50
                trend_desc = "震荡"
            
            # 均线距离分析（价格与均线的偏离度）
            ma5_distance = (current_price - ma5_current) / ma5_current * 100
            ma10_distance = (current_price - ma10_current) / ma10_current * 100
            
            # 如果价格偏离均线过大，降低评分
            if abs(ma5_distance) > 5:  # 偏离5%以上
                trend_score *= 0.8
            if abs(ma10_distance) > 8:  # 偏离8%以上
                trend_score *= 0.9
            
            return {
                'trend_score': round(trend_score, 1),
                'trend_desc': trend_desc,
                'current_price': current_price,
                'ma5': ma5_current,
                'ma10': ma10_current,
                'ma20': ma20_current,
                'ma5_distance': ma5_distance,
                'ma10_distance': ma10_distance
            }
            
        except Exception as e:
            print(f"   ❌ 趋势分析失败: {e}")
            return {'trend_score': 50, 'trend_desc': '分析失败'}
    
    def analyze_momentum(self, data):
        """分析动量（专门为周收益优化）"""
        try:
            close = data['close']
            
            # 计算RSI
            rsi = self.calculate_rsi(close, self.weekly_params['rsi_period'])
            rsi_current = rsi.iloc[-1]
            
            # 计算MACD
            macd_data = self.calculate_macd(close)
            macd_current = macd_data['macd'].iloc[-1]
            signal_current = macd_data['signal'].iloc[-1]
            histogram_current = macd_data['histogram'].iloc[-1]
            
            # 动量评分
            momentum_score = 0
            
            # RSI评分（周收益优化）
            if 30 <= rsi_current <= 70:
                # 在合理区间，有上涨空间
                if 40 <= rsi_current <= 60:
                    momentum_score += 40  # 最佳区间
                elif 30 <= rsi_current <= 40:
                    momentum_score += 35  # 偏低，有反弹空间
                else:  # 60-70
                    momentum_score += 30  # 偏高，但还可以
            elif rsi_current < 30:
                momentum_score += 45  # 超卖，反弹机会
            else:  # rsi_current > 70
                momentum_score += 15  # 超买，风险较大
            
            # MACD评分
            if macd_current > signal_current:
                if histogram_current > 0:
                    momentum_score += 35  # 金叉且柱状图为正
                else:
                    momentum_score += 25  # 金叉但柱状图转负
            else:
                if histogram_current > 0:
                    momentum_score += 20  # 死叉但柱状图为正
                else:
                    momentum_score += 10  # 死叉且柱状图为负
            
            # MACD变化趋势
            if len(macd_data['histogram']) >= 2:
                histogram_change = macd_data['histogram'].iloc[-1] - macd_data['histogram'].iloc[-2]
                if histogram_change > 0:
                    momentum_score += 10  # 柱状图上升
                else:
                    momentum_score -= 5   # 柱状图下降
            
            # 价格动量
            if len(close) >= 5:
                price_momentum = (close.iloc[-1] - close.iloc[-5]) / close.iloc[-5] * 100
                if price_momentum > 3:
                    momentum_score += 15
                elif price_momentum > 1:
                    momentum_score += 10
                elif price_momentum < -3:
                    momentum_score -= 10
            
            return {
                'momentum_score': round(min(momentum_score, 100), 1),
                'rsi_value': rsi_current,
                'macd_value': macd_current,
                'signal_value': signal_current,
                'histogram_value': histogram_current,
                'rsi_signal': self._get_rsi_signal(rsi_current),
                'macd_signal': self._get_macd_signal(macd_current, signal_current)
            }
            
        except Exception as e:
            print(f"   ❌ 动量分析失败: {e}")
            return {'momentum_score': 50}
    
    def analyze_volume(self, data):
        """分析成交量（量价配合）"""
        try:
            close = data['close']
            volume = data['volume']
            
            # 计算成交量均线
            volume_ma = self.calculate_ma(volume, self.weekly_params['volume_ma'])
            current_volume = volume.iloc[-1]
            avg_volume = volume_ma.iloc[-1]
            
            # 成交量评分
            volume_score = 0
            
            # 成交量放大情况
            volume_ratio = current_volume / avg_volume if avg_volume > 0 else 1
            
            # 价格变化
            if len(close) >= 2:
                price_change = (close.iloc[-1] - close.iloc[-2]) / close.iloc[-2] * 100
                
                # 量价配合分析
                if price_change > 0:  # 上涨
                    if volume_ratio > 1.5:
                        volume_score += 40  # 放量上涨
                    elif volume_ratio > 1.2:
                        volume_score += 30  # 温和放量上涨
                    else:
                        volume_score += 15  # 缩量上涨
                else:  # 下跌
                    if volume_ratio > 1.5:
                        volume_score += 10  # 放量下跌（可能是洗盘）
                    elif volume_ratio < 0.8:
                        volume_score += 25  # 缩量下跌（抛压不大）
                    else:
                        volume_score += 15  # 正常下跌
            
            # 成交量趋势
            if len(volume_ma) >= 3:
                volume_trend = volume_ma.iloc[-1] - volume_ma.iloc[-3]
                if volume_trend > 0:
                    volume_score += 20  # 成交量趋势向上
                else:
                    volume_score += 10  # 成交量趋势向下
            
            # 相对成交量水平
            if volume_ratio > 2:
                volume_score += 20  # 异常放量
            elif volume_ratio > 1.2:
                volume_score += 15  # 温和放量
            elif volume_ratio < 0.5:
                volume_score -= 10  # 严重缩量
            
            return {
                'volume_score': round(min(volume_score, 100), 1),
                'current_volume': current_volume,
                'avg_volume': avg_volume,
                'volume_ratio': volume_ratio,
                'volume_desc': self._get_volume_desc(volume_ratio)
            }
            
        except Exception as e:
            print(f"   ❌ 成交量分析失败: {e}")
            return {'volume_score': 50}
    
    def analyze_volatility_risk(self, data):
        """分析波动率风险"""
        try:
            close = data['close']
            
            # 计算波动率
            volatility = self.calculate_volatility(close, period=10)
            current_volatility = volatility.iloc[-1]
            
            # 波动率评分（低波动率更适合周收益策略）
            volatility_score = 0
            
            if current_volatility < 15:
                volatility_score = 80  # 低波动率
                risk_desc = "低风险"
            elif current_volatility < 25:
                volatility_score = 60  # 中等波动率
                risk_desc = "中等风险"
            elif current_volatility < 35:
                volatility_score = 40  # 高波动率
                risk_desc = "高风险"
            else:
                volatility_score = 20  # 极高波动率
                risk_desc = "极高风险"
            
            # 最大回撤分析
            rolling_max = close.rolling(window=20, min_periods=1).max()
            drawdown = (close - rolling_max) / rolling_max * 100
            max_drawdown = drawdown.min()
            
            # 回撤评分
            if max_drawdown > -5:
                volatility_score += 20  # 小回撤
            elif max_drawdown > -10:
                volatility_score += 10  # 中等回撤
            else:
                volatility_score -= 10  # 大回撤
            
            return {
                'volatility_score': round(min(volatility_score, 100), 1),
                'volatility_value': current_volatility,
                'max_drawdown': max_drawdown,
                'risk_desc': risk_desc
            }
            
        except Exception as e:
            print(f"   ❌ 波动率分析失败: {e}")
            return {'volatility_score': 50}
    
    def analyze_price_position(self, data):
        """分析价格位置"""
        try:
            close = data['close']
            high = data['high']
            low = data['low']
            
            # 计算价格位置
            recent_high = high.rolling(window=20, min_periods=1).max().iloc[-1]
            recent_low = low.rolling(window=20, min_periods=1).min().iloc[-1]
            current_price = close.iloc[-1]
            
            # 价格位置百分比
            if recent_high > recent_low:
                position_pct = (current_price - recent_low) / (recent_high - recent_low) * 100
            else:
                position_pct = 50
            
            # 位置评分
            position_score = 0
            
            if 20 <= position_pct <= 40:
                position_score = 80  # 较低位置，有上升空间
                position_desc = "低位"
            elif 40 <= position_pct <= 60:
                position_score = 60  # 中位
                position_desc = "中位"
            elif 60 <= position_pct <= 80:
                position_score = 40  # 高位
                position_desc = "高位"
            elif position_pct < 20:
                position_score = 70  # 超低位
                position_desc = "超低位"
            else:  # position_pct > 80
                position_score = 20  # 超高位
                position_desc = "超高位"
            
            return {
                'position_score': round(position_score, 1),
                'position_pct': position_pct,
                'position_desc': position_desc,
                'recent_high': recent_high,
                'recent_low': recent_low
            }
            
        except Exception as e:
            print(f"   ❌ 价格位置分析失败: {e}")
            return {'position_score': 50}
    
    def calculate_comprehensive_score(self, trend_analysis, momentum_analysis, volume_analysis, 
                                   volatility_analysis, position_analysis):
        """计算综合技术评分"""
        try:
            weights = self.scoring_weights
            
            total_score = (
                trend_analysis.get('trend_score', 50) * weights['trend_score'] +
                momentum_analysis.get('momentum_score', 50) * weights['momentum_score'] +
                volume_analysis.get('volume_score', 50) * weights['volume_score'] +
                volatility_analysis.get('volatility_score', 50) * weights['volatility_score'] +
                position_analysis.get('position_score', 50) * weights['position_score']
            )
            
            return round(total_score, 1)
            
        except Exception as e:
            print(f"   ❌ 综合评分计算失败: {e}")
            return 50.0
    
    def generate_trading_signal(self, trend_analysis, momentum_analysis, volume_analysis, 
                              volatility_analysis, comprehensive_score):
        """生成交易信号"""
        try:
            # 基于综合评分和各项分析生成信号
            signal = "观望"
            confidence = 0
            
            if comprehensive_score >= 80:
                signal = "强烈买入"
                confidence = 90
            elif comprehensive_score >= 70:
                signal = "买入"
                confidence = 80
            elif comprehensive_score >= 60:
                signal = "可买入"
                confidence = 70
            elif comprehensive_score >= 50:
                signal = "持有"
                confidence = 60
            elif comprehensive_score >= 40:
                signal = "观望"
                confidence = 50
            else:
                signal = "回避"
                confidence = 30
            
            # 风险调整
            if volatility_analysis.get('volatility_value', 20) > 30:
                confidence *= 0.8  # 高波动率降低信心
            
            # 趋势确认
            if trend_analysis.get('trend_score', 50) < 40:
                confidence *= 0.9  # 趋势不好降低信心
            
            return {
                'signal': signal,
                'confidence': round(confidence, 1),
                'risk_level': volatility_analysis.get('risk_desc', '中等风险')
            }
            
        except Exception as e:
            print(f"   ❌ 交易信号生成失败: {e}")
            return {'signal': '观望', 'confidence': 50}
    
    def _get_rsi_signal(self, rsi_value):
        """获取RSI信号描述"""
        if rsi_value < 30:
            return "超卖"
        elif rsi_value < 40:
            return "偏弱"
        elif rsi_value < 60:
            return "中性"
        elif rsi_value < 70:
            return "偏强"
        else:
            return "超买"
    
    def _get_macd_signal(self, macd_value, signal_value):
        """获取MACD信号描述"""
        if macd_value > signal_value:
            return "金叉"
        else:
            return "死叉"
    
    def _get_volume_desc(self, volume_ratio):
        """获取成交量描述"""
        if volume_ratio > 2:
            return "放量"
        elif volume_ratio > 1.2:
            return "温和放量"
        elif volume_ratio < 0.8:
            return "缩量"
        else:
            return "正常"
    
    def analyze_single_stock(self, stock_info):
        """分析单只股票"""
        stock_code = stock_info['code']
        stock_name = stock_info['name']
        
        print(f"\n📊 技术分析: {stock_code} {stock_name}")
        print("-" * 60)
        
        # 获取历史数据
        stock_data = self.get_stock_data(stock_code)
        if stock_data is None:
            print(f"   ❌ 获取历史数据失败或数据不足")
            return None
        
        print(f"   ✅ 获取 {len(stock_data)} 天历史数据")
        
        # 进行各项技术分析
        trend_analysis = self.analyze_trend(stock_data)
        momentum_analysis = self.analyze_momentum(stock_data)
        volume_analysis = self.analyze_volume(stock_data)
        volatility_analysis = self.analyze_volatility_risk(stock_data)
        position_analysis = self.analyze_price_position(stock_data)
        
        # 计算综合评分
        comprehensive_score = self.calculate_comprehensive_score(
            trend_analysis, momentum_analysis, volume_analysis, 
            volatility_analysis, position_analysis
        )
        
        # 生成交易信号
        trading_signal = self.generate_trading_signal(
            trend_analysis, momentum_analysis, volume_analysis, 
            volatility_analysis, comprehensive_score
        )
        
        # 输出分析结果
        print(f"   📈 趋势分析: {trend_analysis['trend_desc']} (评分: {trend_analysis['trend_score']})")
        print(f"      当前价: {trend_analysis['current_price']:.2f}, MA5: {trend_analysis['ma5']:.2f}")
        
        print(f"   ⚡ 动量分析: RSI {momentum_analysis['rsi_signal']}({momentum_analysis['rsi_value']:.1f}), MACD {momentum_analysis['macd_signal']}")
        print(f"      动量评分: {momentum_analysis['momentum_score']}")
        
        print(f"   📊 成交量: {volume_analysis['volume_desc']} (评分: {volume_analysis['volume_score']})")
        print(f"      成交量比: {volume_analysis['volume_ratio']:.2f}")
        
        print(f"   📉 风险评估: {volatility_analysis['risk_desc']} (评分: {volatility_analysis['volatility_score']})")
        print(f"      波动率: {volatility_analysis['volatility_value']:.1f}%")
        
        print(f"   🎯 价格位置: {position_analysis['position_desc']} (评分: {position_analysis['position_score']})")
        
        print(f"   🏆 综合评分: {comprehensive_score}/100")
        print(f"   💡 交易建议: {trading_signal['signal']} (置信度: {trading_signal['confidence']}%)")
        
        # 组装结果
        result = {
            **stock_info,
            'technical_score': comprehensive_score,
            'trading_signal': trading_signal['signal'],
            'signal_confidence': trading_signal['confidence'],
            'risk_level': trading_signal['risk_level'],
            'trend_analysis': trend_analysis,
            'momentum_analysis': momentum_analysis,
            'volume_analysis': volume_analysis,
            'volatility_analysis': volatility_analysis,
            'position_analysis': position_analysis,
            'data_points': len(stock_data)
        }
        
        return result
    
    def run_technical_analysis(self, screening_file="test_screening_results.csv"):
        """运行技术分析系统"""
        self.print_header("第三步：技术分析系统 - 优化版本")
        
        # 记录开始时间
        self.analysis_stats['start_time'] = datetime.now()
        
        # 加载筛选结果
        try:
            df = pd.read_csv(screening_file)
            screened_stocks = df.to_dict('records')
            
            # 转换列名（适配第二步的输出格式）
            for stock in screened_stocks:
                if '股票代码' in stock:
                    stock['code'] = stock['股票代码']
                if '股票名称' in stock:
                    stock['name'] = stock['股票名称']
                if '当前价格' in stock:
                    stock['current_price'] = stock['当前价格']
                if '市值(亿)' in stock:
                    stock['market_cap'] = stock['市值(亿)']
                if '筛选评分' in stock:
                    stock['screening_score'] = stock['筛选评分']
                    
        except Exception as e:
            print(f"❌ 加载筛选结果失败: {e}")
            print(f"💡 请先运行第二步股票筛选系统")
            return []
        
        print(f"📋 开始对 {len(screened_stocks)} 只候选股票进行技术分析...")
        self.analysis_stats['total_stocks'] = len(screened_stocks)
        
        technical_results = []
        
        for i, stock_info in enumerate(screened_stocks, 1):
            print(f"\n[{i:2d}/{len(screened_stocks)}] 技术分析进度")
            
            try:
                result = self.analyze_single_stock(stock_info)
                if result:
                    technical_results.append(result)
                    self.analysis_stats['successful_analysis'] += 1
                else:
                    self.analysis_stats['failed_analysis'] += 1
            except Exception as e:
                print(f"   ❌ 分析失败: {e}")
                self.analysis_stats['failed_analysis'] += 1
        
        # 记录结束时间
        self.analysis_stats['end_time'] = datetime.now()
        
        # 按技术评分排序
        technical_results.sort(key=lambda x: x['technical_score'], reverse=True)
        
        # 生成技术分析报告
        self.generate_technical_report(technical_results)
        
        return technical_results
    
    def generate_technical_report(self, technical_results):
        """生成技术分析报告"""
        print(f"\n📊 技术分析结果统计:")
        print(f"   • 分析股票数量: {self.analysis_stats['total_stocks']}")
        print(f"   • 成功分析: {self.analysis_stats['successful_analysis']}")
        print(f"   • 失败分析: {self.analysis_stats['failed_analysis']}")
        
        if len(technical_results) > 0:
            avg_score = sum(r['technical_score'] for r in technical_results) / len(technical_results)
            print(f"   • 平均技术评分: {avg_score:.1f}")
            
            # 计算各评分区间分布
            high_score = len([r for r in technical_results if r['technical_score'] >= 70])
            medium_score = len([r for r in technical_results if 50 <= r['technical_score'] < 70])
            low_score = len([r for r in technical_results if r['technical_score'] < 50])
            
            print(f"   • 高评分股票(≥70): {high_score} 只")
            print(f"   • 中评分股票(50-70): {medium_score} 只")
            print(f"   • 低评分股票(<50): {low_score} 只")
            
            print(f"\n🏆 技术分析排行榜:")
            print(f"{'排名':<4} {'代码':<8} {'名称':<12} {'筛选评分':<8} {'技术评分':<8} {'信号':<8} {'置信度':<8}")
            print("-" * 80)
            
            for i, result in enumerate(technical_results, 1):
                print(f"{i:<4} {result['code']:<8} {result['name']:<12} "
                      f"{result.get('screening_score', 0):<8.1f} {result['technical_score']:<8.1f} "
                      f"{result['trading_signal']:<8} {result['signal_confidence']:<8.1f}")
            
            # 推荐股票
            print(f"\n🎯 本周技术面推荐 (技术评分≥70且信号为买入):")
            recommended_stocks = [
                r for r in technical_results 
                if r['technical_score'] >= 70 and r['trading_signal'] in ['强烈买入', '买入', '可买入']
            ]
            
            if recommended_stocks:
                for i, stock in enumerate(recommended_stocks, 1):
                    print(f"   {i}. {stock['code']} {stock['name']} - 技术评分: {stock['technical_score']:.1f}")
                    print(f"      信号: {stock['trading_signal']} (置信度: {stock['signal_confidence']:.1f}%)")
                    print(f"      风险: {stock['risk_level']}")
            else:
                print(f"   暂无技术面强烈推荐的股票")
                print(f"   建议关注技术评分>60的股票，等待更好的入场时机")
        else:
            print(f"   ⚠️ 没有成功完成技术分析的股票")
    
    def save_technical_results(self, technical_results, filename="technical_analysis_results.csv"):
        """保存技术分析结果"""
        if technical_results:
            # 准备保存数据
            save_data = []
            for result in technical_results:
                save_record = {
                    '排名': technical_results.index(result) + 1,
                    '股票代码': result['code'],
                    '股票名称': result['name'],
                    '当前价格': result['current_price'],
                    '市值(亿)': result['market_cap'],
                    '筛选评分': result.get('screening_score', 0),
                    '技术评分': result['technical_score'],
                    '交易信号': result['trading_signal'],
                    '信号置信度': result['signal_confidence'],
                    '风险等级': result['risk_level'],
                    '趋势评分': result['trend_analysis']['trend_score'],
                    '动量评分': result['momentum_analysis']['momentum_score'],
                    '成交量评分': result['volume_analysis']['volume_score'],
                    '波动率评分': result['volatility_analysis']['volatility_score'],
                    '价格位置评分': result['position_analysis']['position_score'],
                    '分析时间': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                }
                save_data.append(save_record)
            
            # 保存到CSV
            df = pd.DataFrame(save_data)
            df.to_csv(filename, index=False, encoding='utf-8-sig')
            print(f"\n💾 技术分析结果已保存到 {filename}")
            
            return filename
        else:
            print(f"\n⚠️ 没有技术分析结果需要保存")
            return None
    
    def get_analysis_stats(self):
        """获取分析统计信息"""
        if self.analysis_stats['end_time'] and self.analysis_stats['start_time']:
            processing_time = (self.analysis_stats['end_time'] - self.analysis_stats['start_time']).total_seconds()
            self.analysis_stats['processing_time'] = processing_time
        
        return self.analysis_stats.copy()

if __name__ == "__main__":
    # 创建优化版技术分析系统
    tech_analyzer = OptimizedTechnicalAnalysis()
    
    # 执行技术分析
    results = tech_analyzer.run_technical_analysis()
    
    # 保存结果
    if results:
        tech_analyzer.save_technical_results(results)
    
    # 获取统计信息
    stats = tech_analyzer.get_analysis_stats()
    
    print(f"\n🎉 第三步：技术分析系统优化完成！")
    print(f"   • 成功分析 {stats['successful_analysis']} 只股票")
    print(f"   • 处理时间: {stats.get('processing_time', 0):.1f}秒")
    print(f"   • 准备进入第四步：基本面分析系统")
